package cn.fintecher.pangolin.service.manage.service;

import cn.fintecher.pangolin.entity.elastic.SystemLog;
import cn.fintecher.pangolin.entity.elastic.SystemLoginLog;
import cn.fintecher.pangolin.service.manage.elastic.SystemLogElastic;
import cn.fintecher.pangolin.service.manage.elastic.SystemLoginLogElastic;
import cn.fintecher.pangolin.service.manage.request.FindLoginRequest;
import cn.fintecher.pangolin.service.manage.request.FindSystemLogRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 15:18 2019/8/23
 */

@Service("systemLogService")
@Transactional(rollbackFor = Exception.class)
public class SystemLogService {
    @Autowired
    private SystemLoginLogElastic systemLoginLogElastic;

    @Autowired
    private SystemLogElastic systemLogElastic;

    /**
     * 系统登录日志查询
     */
    public Page<SystemLoginLog> findAllLoginLog(FindLoginRequest request, Pageable pageable) {
        BoolQueryBuilder builder = request.generateBuilder();
        FieldSortBuilder sort = SortBuilders.fieldSort("loginTime").unmappedType("date").order(SortOrder.DESC);
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).withPageable(pageable).withSort(sort).build();
        return systemLoginLogElastic.search(searchQuery);
    }

    /**
     * 批量删除登录日志
     */
    public void batchDeleteLog(List<String> ids) {
        Iterable<SystemLoginLog> iterable = systemLoginLogElastic.findAllById(ids);
        systemLoginLogElastic.deleteAll(iterable);
    }

    /**
     * 系统日志查询
     */
    public Page<SystemLog> findAllSystemLog(FindSystemLogRequest request, Pageable pageable) {
        BoolQueryBuilder builder = request.getBuilder();
        SortBuilder sortBuilder = SortBuilders.fieldSort("operateTime").unmappedType("date").order(SortOrder.DESC);
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).withSort(sortBuilder).withPageable(pageable).build();
        return systemLogElastic.search(searchQuery);
    }

    /**
     * 批量删除系统日志
     */
    public void batchDeleteSystemLog(List<String> ids) {
        Iterable<SystemLog> iterable = systemLogElastic.findAllById(ids);
        systemLogElastic.deleteAll(iterable);
    }
}
